package com.choosefine.it.manager.controller;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.choosefine.it.base.BaseController;
import com.choosefine.it.base.dto.PageDTO;
import com.choosefine.it.common.def.ResultCode;
import com.choosefine.it.common.model.CustomRestTemplate;
import com.choosefine.it.common.utils.DateUtils;
import com.choosefine.it.common.utils.IdsUtil;
import com.choosefine.it.common.utils.StringUtils;
import com.choosefine.it.common.utils.URLHandlerUtils;
import com.choosefine.it.manager.model.ManagerFindprojectInfo;
import com.choosefine.it.manager.model.dto.SelectManagerFindProjectinfoByConditionDTO;
import com.choosefine.it.manager.model.dto.UpdateManagerFindProjectVerifyStatusDTO;
import com.choosefine.it.manager.model.po.ManagerFindprojectInfoPO;
import com.choosefine.it.manager.model.vo.ManagerFindprojectInfoDetailVO;
import com.choosefine.it.manager.model.vo.ManagerFindprojectInfoVO;
import com.choosefine.it.manager.service.ManagerFindprojectInfoService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.Page;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import springfox.documentation.annotations.ApiIgnore;

/**
 * @author 潘钱钦 下午8:19:46
 *
 */
@RestController
@RequestMapping("/manager/ManagerFindproject")
@Api(value = "项目经理发布找项目以及管理", description = "潘钱钦")
public class ManagerFindprojectInfoController extends BaseController {
	@Autowired
	private ManagerFindprojectInfoService managerFindprojectInfoService;
	@Autowired
	CustomRestTemplate restTemplate;
	@Autowired
	ObjectMapper jsonObjectMapper;
	Logger logger = LoggerFactory.getLogger(ManagerFindprojectInfoController.class);
	@Value("#{yaml.get('basedata.userinfo.getUserByUserCode')}")
	String userInfoURL = null;

	@ApiOperation("添加找项目的信息")
	@RequestMapping(value = "/publishFindprojectInfo", method = RequestMethod.POST)
	public String publishFindprojectInfo(@RequestBody ManagerFindprojectInfoPO managerFindprojectInfoPo)
			throws JsonProcessingException {
		String result = null;
		//必填数据校验
		if (managerFindprojectInfoPo!=null&&StringUtils.isNotBlank(managerFindprojectInfoPo.getUserCode())
				&& StringUtils.isNotBlank(managerFindprojectInfoPo.getExpectProjectTypeId())
				&& StringUtils.isNotBlank(managerFindprojectInfoPo.getExpectProjectTypeName())
				&& StringUtils.isNotBlank(managerFindprojectInfoPo.getProjectManagerName())
				&& StringUtils.isNotBlank(managerFindprojectInfoPo.getPhone())) {
				ManagerFindprojectInfo m = dataCheck(managerFindprojectInfoPo);
				Integer isSuccess = managerFindprojectInfoService.addFindProject(m);
				if (isSuccess.intValue() > 0) {
					result = responseSuccess(isSuccess, ResultCode.SUCCESS, ResultCode.MSG_SUCCESS);
				} else {
				result = responseFail(ResultCode.MSG_USERNOTEXIT);
			}
		} else {
			result = responseFail(ResultCode.MSG_PARAMS_NULL);
		}
		return result;
	}
	
	/**
	 * 插入数据模型转换
	 *  juchengyang 2017年3月8日
	 */
	private ManagerFindprojectInfo dataCheck(ManagerFindprojectInfoPO managerFindprojectInfoPo) {
		ManagerFindprojectInfo m;
		m = new ManagerFindprojectInfo();
		if (managerFindprojectInfoPo.getPublisher() != null
				&& !"".equals(managerFindprojectInfoPo.getPublisher())) {// 判断是否是控制台那边的操作员发布的。
			m.setPublisher(managerFindprojectInfoPo.getPublisher());
			m.setVerifyStatus(1);
		} else {
			m.setVerifyStatus(0);
		}
		m.setCtime(DateUtils.getNowTime());
		m.setProvinceCode(managerFindprojectInfoPo.getProvinceCode());
		m.setProvinceName(managerFindprojectInfoPo.getProvinceName());
		m.setCityCode(managerFindprojectInfoPo.getCityCode());
		m.setCityName(managerFindprojectInfoPo.getCityName());
		m.setExpectProjectTime(managerFindprojectInfoPo.getExpectProjectTime());
		m.setExpectProjectTypeId(managerFindprojectInfoPo.getExpectProjectTypeId());
		m.setExpectProjectTypeName(managerFindprojectInfoPo.getExpectProjectTypeName());
		m.setPhone(managerFindprojectInfoPo.getPhone());
		m.setProjectManagerName(managerFindprojectInfoPo.getProjectManagerName());
		m.setSparePhone(managerFindprojectInfoPo.getSparePhone());
		m.setUserCode(managerFindprojectInfoPo.getUserCode());
		m.setPublishTime(DateUtils.getNowTime());
		m.setPhone(managerFindprojectInfoPo.getPhone());
		//add by juchengyang 2017/2/25
		m.setReleaseNo("MFP"+ System.currentTimeMillis());
		m.setSkillCertificateName(managerFindprojectInfoPo.getSkillCertificateName());
		m.setDescribe(managerFindprojectInfoPo.getDescribe());
		m.setPublishStatus(0);
		m.setUuid(managerFindprojectInfoPo.getUuid());
		return m;
	}

	@ApiOperation(value = "软删除某条发布求项目的信息", notes = "")
	@ApiImplicitParam(name = "id", value = "该条记录的id", required = true, dataType = "Integer", paramType = "path")
	@RequestMapping(value = "/deleteManagerFindprojectInfo/{id}", method = RequestMethod.PUT)
	public String deleteManagerFindprojectInfoById(@PathVariable Integer id) {
		String result = null;
		if (id != null) {
			Map<String, Object> params = new HashMap<>();
			params.put("id", id);
			params.put("utime", DateUtils.getNowTime());
			Integer isSuccess = managerFindprojectInfoService.deleteManagerFindprojectInfoById(params);
			if (isSuccess.intValue() > 0) {
				result = responseSuccess(isSuccess, ResultCode.SUCCESS, ResultCode.MSG_SUCCESS);
			} else {
				result = responseFail(ResultCode.FAILED, ResultCode.MSG_UPDATE_ERROR);
			}
		} else {
			result = responseFail(ResultCode.FAILED, ResultCode.MSG_PARAMS_NULL);
		}
		return result;
	}

	@ApiOperation(value = "修改某条发布求项目信息的发布状态", notes = "")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "publishStatus", value = "发布状态0开始找1停止找", required = true, dataType = "Integer", paramType = "path"),
			@ApiImplicitParam(name = "id", value = "该条记录的id", required = true, dataType = "Integer", paramType = "path") })
	@RequestMapping(value = "/updateState/{id}/{publishStatus}", method = RequestMethod.PUT)
	public String updateStateById(@PathVariable Integer id, @PathVariable Integer publishStatus) throws Exception {
		String result = null;
		if (id != null && publishStatus != null&&publishStatus != 1 || publishStatus != 0) {
			Map<String, Object> params = new HashMap<>();
			params.put("id", id);
			params.put("utime", DateUtils.getNowTime());
			params.put("publishStatus", publishStatus);
			Integer isSuccess = managerFindprojectInfoService.updateManagerFindprojectInfoStateById(params);
			if (isSuccess.intValue() > 0) {
				result = responseSuccess(isSuccess, ResultCode.SUCCESS, ResultCode.MSG_SUCCESS);
			} else {
				result = responseFail(ResultCode.FAILED, ResultCode.MSG_UPDATE_ERROR);
			}
		} else {
			result = responseFail(ResultCode.FAILED, ResultCode.MSG_PARAMS_NULL);
		}
		return result;
	}

	@ApiOperation(value = "根据用户的usercode查看发布的找项目列表", notes = "")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "userCode", value = "用户的唯一编号", required = true, dataType = "String", paramType = "path"),
			@ApiImplicitParam(name = "pageNum", value = "起始行", required = true, dataType = "Integer", paramType = "path"),
			@ApiImplicitParam(name = "pageSize", value = "一页显示的行数", required = true, dataType = "Integer", paramType = "path"),
			@ApiImplicitParam(name = "verifyStatus", value = "审核状态", required = true, dataType = "Integer", paramType = "path")})
	@RequestMapping(value = "/selectManagerFindprojectInfoList/{userCode}/{verifyStatus}/{pageSize}/{pageNum}", method = RequestMethod.GET)
	public String selectManagerFindprojectInfoListByUserCode(@PathVariable String userCode, @PathVariable Integer pageNum,
			@PathVariable Integer pageSize, @PathVariable Integer verifyStatus) {
		String result = null;
		if (StringUtils.isNotBlank(userCode)) {
			PageDTO page = new PageDTO();
			page.setPageNum(pageNum);
			page.setPageSize(pageSize);
			Map<String, Object> params = new HashMap<>();
			params.put("userCode", userCode);
			params.put("verifyStatus", verifyStatus);
			Page<ManagerFindprojectInfo> list = managerFindprojectInfoService
					.selectManagerFindprojectInfoListByUserCode(params, page);
			if (list.size() > 0) {
				result = responseSuccess(list);
			} else {
				result = responseFail(ResultCode.FAILED, ResultCode.MSG_DATA_ISEMPTY);
			}
		} else {
			result = responseFail(ResultCode.FAILED, ResultCode.MSG_PARAMS_NULL);
		}
		return result;
	}

	@ApiOperation(value = "根据该条记录的id修改该条发布信息")
	@RequestMapping(value = "/upadateManagerFindprojectInfo", method = RequestMethod.POST)
	public String upadateManagerFindprojectInfo(@RequestBody ManagerFindprojectInfoVO mfVo)
			throws JsonProcessingException, Exception {
		String result = null;
		if (null != mfVo && null != mfVo.getUserCode() && !"".equals(mfVo.getUserCode())) {
			String url = URLHandlerUtils.getUrlBuffer(shixiaobaoURL,  userInfoURL).append(mfVo.getUserCode()).toString();
			Map userInfoResultMap = restTemplate.getForObject(url, Map.class, new HashMap());
			Map userInfo = (Map) userInfoResultMap.get("data");
			logger.info("序列化结果 :\n" + jsonObjectMapper.writeValueAsString(userInfo));
			if (userInfo != null) {
				ManagerFindprojectInfo m = updateDataChange(mfVo);
				int isSuccess = managerFindprojectInfoService.updateManagerFindprojectInfo(m);
				if (isSuccess > 0) {
					result = responseSuccess(isSuccess);
				} else {
					result = responseFail(ResultCode.MSG_ERROR);
				}
			} else {
					result = responseFail(ResultCode.MSG_USERNOTEXIT);
			}
		} else {
			result = responseFail(ResultCode.MSG_PARAMS_NULL);
		}
		return result;
	}

	/**
	 * 编辑数据模型转换
	 *  juchengyang 2017年3月8日
	 */
	private ManagerFindprojectInfo updateDataChange(ManagerFindprojectInfoVO mfVo) {
		ManagerFindprojectInfo m = new ManagerFindprojectInfo();
		m.setProvinceCode(mfVo.getProvinceCode());
		m.setProvinceName(mfVo.getProvinceName());
		m.setCityCode(mfVo.getCityCode());
		m.setCityName(mfVo.getCityName());
		m.setExpectProjectTime(mfVo.getExpectProjectTime());
		m.setExpectProjectTypeId(mfVo.getExpectProjectTypeId());
		m.setExpectProjectTypeName(mfVo.getExpectProjectTypeName());
		m.setSparePhone(mfVo.getSparePhone());
		m.setId(mfVo.getId());
		m.setReleaseNo("MFP"+ System.currentTimeMillis());
		m.setSkillCertificateName(mfVo.getSkillCertificateName());
		m.setDescribe(mfVo.getDescribe());
		m.setUtime(System.currentTimeMillis());
		return m;
	}

	@ApiOperation(value = "根据该条记录的id查看该条发布记录的详细信息")
	@RequestMapping(value = "/getManagerFindprojectInfoById/{id}", method = RequestMethod.GET)
	public String getManagerFindprojectInfoById(@PathVariable Integer id)
			throws JsonProcessingException, Exception {
		if (id.intValue()>0) {
			ManagerFindprojectInfo managerFindprojectInfo=managerFindprojectInfoService.getManagerFindprojectInfoById(id);
			if(managerFindprojectInfo!=null){
				return responseSuccess(managerFindprojectInfo, ResultCode.SUCCESS, ResultCode.MSG_QUERY_SUCCESS);
			}else{
				return responseFail(ResultCode.MSG_DATA_ISEMPTY);
			}
		}
		return responseFail(ResultCode.MSG_PARAMS_ERROR);	
	}
	
	@ApiIgnore
	@RequestMapping(value = "/selectFindProjectInfoByCondition", method = RequestMethod.POST)
	public String selectFindProjectInfoByCondition(@RequestBody SelectManagerFindProjectinfoByConditionDTO dto) throws UnsupportedEncodingException {
		String result = null;
		PageDTO page = new PageDTO();
		page.setPageNum(dto.getPageNum());
		page.setPageSize(dto.getPageSize());
		Map<String, Object> params = new HashMap<>();
		if (!StringUtils.isEmpty(dto.getUserCode())) {
			params.put("userCode", dto.getUserCode());
		}
		if (!StringUtils.isEmpty(dto.getExpectProjectTypeName())) {
			params.put("expectProjectType", dto.getExpectProjectTypeName());
		}
		if (dto.getStartTime() != null) {
			params.put("startTime", dto.getStartTime());
		}
		if (dto.getEndTime() != null) {
			params.put("endTime", dto.getEndTime());
		}
		if (dto.getVerifyStatus() != null) {
			params.put("verifyStatus", dto.getVerifyStatus());
		}
		Page<ManagerFindprojectInfo> list = managerFindprojectInfoService.selectFindProjectInfoByCondition(params,
				page);
		result = responseSuccess(list.toPageInfo());
		return result;
	}

	@ApiIgnore
	@RequestMapping(value = "/updateManagerFindProjectVerifyStatus", method = RequestMethod.PUT)
	public String updateManagerFindProjectVerifyStatus(@RequestBody UpdateManagerFindProjectVerifyStatusDTO dto) {
		String result = null;
		Map<String, Object> params = new HashMap<>();
		if (null != dto && dto.getId() != null
				&& !StringUtils.isEmpty(dto.getPublisher())
				&& dto.getVerifyStatus() != null) {
			params.put("id", dto.getId());
			params.put("verifyStatus", dto.getVerifyStatus());
			params.put("utime", DateUtils.getNowTime());
			params.put("publisher", dto.getPublisher());
			if (!StringUtils.isEmpty(dto.getReason())){
				params.put("reason", dto.getReason());
			}
			int isSuccess = managerFindprojectInfoService.updateFindProjectVerifyStatus(params);
			if (isSuccess > 0) {
				result = responseSuccess(isSuccess, ResultCode.MSG_UPDATE_SUCCESS);
			} else {
				result = responseFail(ResultCode.MSG_UPDATE_FAILD);
			}
		} else {
			responseFail(ResultCode.MSG_PARAMS_ERROR);
		}
		return result;
	}

	@ApiIgnore
	@RequestMapping(value = "/deleteManagerFindProject/{idss}", method = RequestMethod.GET)
	public String deleteManagerFindProject(@PathVariable String idss) throws  Exception{
		List<Integer> ids = new ArrayList<>();
		String result = null;
		Map<String, Object> params = new HashMap<>();
		ids=IdsUtil.getIds(idss);
		if (ids.size() > 0) {
			params.put("ids", ids);
			params.put("utime", DateUtils.getNowTime());
			int isSuccess = managerFindprojectInfoService.deleteFindProject(params);
			if (isSuccess == ids.size()) {
				result = responseSuccess(isSuccess, ResultCode.MSG_UPDATE_SUCCESS);
			} else result = responseFail(ResultCode.MSG_UPDATE_FAILD);
		} else {
			responseFail(ResultCode.MSG_PARAMS_ERROR);
		}
		return result;
	}

}
